package com.example.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class RequestUtil {

	private static final Logger logger = LoggerFactory.getLogger(RequestUtil.class);

	public static final String OS_WINDOWS = "window";

	public static final String OS_LINUX = "linux";

	public static String getIpAddr(HttpServletRequest request) {
		// 结合网关代理，获取IP
		String ip = request.getHeader("x-forwarded-for");
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		} else {
			ip = ip.split(",")[0];
		}
		return ip;
	}

	public static String getMac(HttpServletRequest request) {
		String mac = "";
		request.getHeader("Proxy-Client-MAC");
		if (StringUtils.isEmpty(mac) || "unknown".equalsIgnoreCase(mac)) {
			mac = request.getParameter("Proxy-Client-MAC");
		}
		if (StringUtils.isEmpty(mac) || "unknown".equalsIgnoreCase(mac)) {
			mac = "";
		}
		return mac;
	}

	public static String getClientOS(HttpServletRequest request) {
		String userAgent = request.getHeader("User-Agent").toLowerCase();
		logger.info("客户端代理标识：{}",userAgent);
		if(userAgent.contains(OS_WINDOWS)) {
			return OS_WINDOWS;
		}else if(userAgent.contains(OS_LINUX)){
			return OS_LINUX;
		}
		logger.info("无法解析没有找到对应的客户端代理标识,使用默认windows");
		return  OS_WINDOWS;
	}
}
